﻿using STTech.BytesIO.Tcp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF.BytesIO.TCPClient.Models;
using WPF.BytesIO.TCPClient.ModelViews;

namespace WPF.BytesIO.TCPClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainViewModel ViewModel { get { return App.MainViewModel; } }

        TcpClient _tcpClient;

        public MainWindow()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            InitializeComponent();

            this.Loaded += delegate
            {
                this.DataContext = ViewModel;

                _tcpClient = new TcpClient();

                _tcpClient.OnDataReceived += _tcpClient_OnDataReceived;

                _tcpClient.OnConnectedSuccessfully += _tcpClient_OnConnectedSuccessfully;

                _tcpClient.OnDisconnected += _tcpClient_OnDisconnected;




            };

            this.Closing += delegate
            {
                if (this._tcpClient.IsConnected)
                    this._tcpClient.Disconnect();
            };
        }

        #region 打印log
        private Block Print(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtLogName.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = Print(data, statusBrush);
                });
            }

            return block;
        }
        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }
        private void tbnCleanRickTextBoxContent_OnClick(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                rtxtLogName.Document.Blocks.Clear();
            });
        }
        #endregion

        private void btnLinkServer_OnClick(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(ViewModel.TestInfo.ClientIp) || ViewModel.TestInfo.ClientPort == 0)
            {
                Print("IP或Port不能为空", MyBrushes.FAIL);
                return;
            }
            if (!_tcpClient.IsConnected)
            {
                _tcpClient.Host = ViewModel.TestInfo.ClientIp;

                _tcpClient.Port = ViewModel.TestInfo.ClientPort;

                var msg = _tcpClient.Connect();

                if (msg.IsSuccess)
                {
                    ViewModel.TCPStatus.Update($"已连接", MyBrushes.Green);
                }
                else
                {
                    ViewModel.TCPStatus.Update($"未连接", MyBrushes.Red);
                }
            }
            else
            {
                Print($"[{_tcpClient.Host}:{_tcpClient.Port}]已连接", MyBrushes.RichBlue);
            }
        }

        private void _tcpClient_OnDisconnected(object sender, STTech.BytesIO.Core.DisconnectedEventArgs e)
        {
            if (_tcpClient.IsConnected)
            {
                ViewModel.TCPStatus.Update($"已连接", MyBrushes.Green);
            }
            else
            {
                ViewModel.TCPStatus.Update($"未连接", MyBrushes.Red);
            }
        }

        private void _tcpClient_OnConnectedSuccessfully(object sender, STTech.BytesIO.Core.ConnectedSuccessfullyEventArgs e)
        {
            ViewModel.TCPStatus.Update($"已连接", MyBrushes.Green);
        }

        private void _tcpClient_OnDataReceived(object sender, STTech.BytesIO.Core.DataReceivedEventArgs e)
        {
            Print($"收到数据：{e.Data.EncodeToString("UTF-8")}",MyBrushes.Green);
        }

        private void btnCloseLink_OnClick(object sender, RoutedEventArgs e)
        {
            Print($"[{_tcpClient.Host}:{_tcpClient.Port}]断开连接", MyBrushes.RichBlue);
            _tcpClient?.Disconnect();
            
        }

        private void btnH_PowerOn_OnClick(object sender, RoutedEventArgs e)
        {
            if (_tcpClient !=null && _tcpClient.IsConnected)
            {
                _tcpClient.SendAsync(Encoding.UTF8.GetBytes("H_PowerOn"));
            }
        }

        private void btnL_PowerOnClick(object sender, RoutedEventArgs e)
        {
            if (_tcpClient != null && _tcpClient.IsConnected)
            {
                _tcpClient.SendAsync(Encoding.UTF8.GetBytes("L_PowerOn"));
            }
        }

        private void btnPowerOff_OnClick(object sender, RoutedEventArgs e)
        {
            if (_tcpClient != null && _tcpClient.IsConnected)
            {
                _tcpClient.SendAsync(Encoding.UTF8.GetBytes("PowerOff"));
            }
        }

        private void btnSend_OnClick(object sender, RoutedEventArgs e)
        {
            if (_tcpClient != null && _tcpClient.IsConnected)
            {
                _tcpClient.SendAsync(Encoding.UTF8.GetBytes(ViewModel.TestInfo.ClientSendMsg));
            }
        }

        private void btnE_TestClick(object sender, RoutedEventArgs e)
        {
            if (_tcpClient != null && _tcpClient.IsConnected)
            {
                _tcpClient.SendAsync(Encoding.UTF8.GetBytes("E_Test"));
            }
        }
    }
}
